package com.example.baselibrary.utlis

import android.os.Looper
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import kotlin.coroutines.CoroutineContext

/**
 * 基于 Kotlin 协程的线程管理工具类
 * 提供多优先级线程调度和协程管理功能
 */
object ThreadManagerKt {
    // 应用级协程作用域
    private val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)

    // 原子任务计数器
    private val activeTaskCount = AtomicInteger(0)

    // 自定义异常处理接口
    interface ExceptionHandler {
        fun handleException(context: CoroutineContext, exception: Throwable)
    }

    private var customExceptionHandler: ExceptionHandler? = null

    // 自定义调度器
    private val highPriorityDispatcher by lazy {
        Executors.newFixedThreadPool(maxOf(2, Runtime.getRuntime().availableProcessors())).asCoroutineDispatcher()
    }

    private val normalPriorityDispatcher by lazy {
        Executors.newFixedThreadPool(maxOf(2, Runtime.getRuntime().availableProcessors() / 2)).asCoroutineDispatcher()
    }

    private val lowPriorityDispatcher by lazy {
        Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    }

    // 默认异常处理器
    private val defaultExceptionHandler = CoroutineExceptionHandler { context, throwable ->
        customExceptionHandler?.handleException(context, throwable)
            ?: android.util.Log.e("ThreadManager", "协程执行异常", throwable)
    }

    // 可取消任务管理
    private val jobMap = mutableMapOf<Int, Job>()
    private var jobId = 0
    private val jobMutex = Mutex()

    /**
     * 设置自定义异常处理器
     */
    fun setExceptionHandler(handler: ExceptionHandler) {
        customExceptionHandler = handler
    }

    /**
     * 判断当前是否为主线程
     */
    fun isMainThread() = Looper.myLooper() == Looper.getMainLooper()

    /**
     * 在UI线程执行任务
     */
    fun runOnUiThread(block: () -> Unit) {
        if (isMainThread()) {
            block()
        } else {
            launchOnMain { block() }
        }
    }

    /**
     * 延迟在UI线程执行任务
     */
    fun runOnUiThreadDelayed(delayMillis: Long, block: () -> Unit) {
        applicationScope.launch(Dispatchers.Main + defaultExceptionHandler) {
            delay(delayMillis)
            block()
        }
    }

    /**
     * 启动不同优先级的后台任务
     */
    fun launchHighPriority(block: suspend CoroutineScope.() -> Unit) =
        launchCoroutine(highPriorityDispatcher, block)

    fun launchNormalPriority(block: suspend CoroutineScope.() -> Unit) =
        launchCoroutine(normalPriorityDispatcher, block)

    fun launchLowPriority(block: suspend CoroutineScope.() -> Unit) =
        launchCoroutine(lowPriorityDispatcher, block)

    fun launchOnMain(block: suspend CoroutineScope.() -> Unit) =
        launchCoroutine(Dispatchers.Main, block)

    /**
     * 启动可取消的任务
     */
    suspend fun launchCancellable(
        dispatcher: CoroutineContext = normalPriorityDispatcher,
        block: suspend CoroutineScope.() -> Unit
    ): Int = jobMutex.withLock {
        val id = jobId++
        activeTaskCount.incrementAndGet()

        val job = applicationScope.launch(dispatcher + defaultExceptionHandler) {
            try {
                block()
            } finally {
                activeTaskCount.decrementAndGet()
                // 使用非挂起方式清理 jobMap
                jobMap.remove(id)
            }
        }

        jobMap[id] = job
        job.invokeOnCompletion { cause ->
            if (cause != null) {
                // 使用非挂起方式清理 jobMap
                jobMap.remove(id)
            }
        }

        return id
    }


    /**
     * 取消指定任务
     */
    suspend fun cancelJob(jobId: Int) {
        jobMutex.withLock {
            jobMap[jobId]?.cancel()
            jobMap.remove(jobId)
        }
    }

    /**
     * 带超时的任务启动
     */
    fun <T> launchWithTimeout(
        timeoutMillis: Long,
        dispatcher: CoroutineContext = normalPriorityDispatcher,
        onTimeout: (() -> Unit)? = null,
        block: suspend CoroutineScope.() -> T
    ) {
        applicationScope.launch(dispatcher + defaultExceptionHandler) {
            try {
                withTimeout(timeoutMillis) {
                    block()
                }
            } catch (e: TimeoutCancellationException) {
                onTimeout?.invoke()
                // 处理超时异常
            }
        }
    }

    /**
     * 核心协程启动方法
     */
    private fun launchCoroutine(
        dispatcher: CoroutineContext,
        block: suspend CoroutineScope.() -> Unit
    ) {
        activeTaskCount.incrementAndGet()
        applicationScope.launch(dispatcher + defaultExceptionHandler) {
            try {
                block()
            } finally {
                activeTaskCount.decrementAndGet()
            }
        }
    }

    /**
     * 优雅关闭所有协程资源
     */
    suspend fun shutdown() {
        // 取消所有任务
        jobMutex.withLock {
            jobMap.values.forEach { it.cancel() }
            jobMap.clear()
        }

        // 等待活跃任务完成或超时
        withTimeoutOrNull(5000) {
            while (activeTaskCount.get() > 0) {
                delay(100)
            }
        }

        // 关闭调度器
        applicationScope.cancel()
        closeDispatcherSafely(highPriorityDispatcher)
        closeDispatcherSafely(normalPriorityDispatcher)
        closeDispatcherSafely(lowPriorityDispatcher)
    }

    private fun closeDispatcherSafely(dispatcher: CoroutineContext) {
        when (dispatcher) {
            is ExecutorCoroutineDispatcher -> dispatcher.close()
            is CloseableCoroutineDispatcher -> dispatcher.close()
            else -> { /* 无需处理 */ }
        }
    }
}